package com.fingard.dsp.bank.helpers.dbhelpers;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.text.StringHelper;

public class UpdateHelper {
	/**更新对象
	 * @param pUpd更新的字段
	 * @param pCond 条件字段
	 * @param pExUpd 附加更新的，ROWVERSION=ROWVERSION+1
	 * @throws Exception */
	public static int updateObject(Connection pConn, String pTabName, Object pObj, ArrayList<String> pUpd, ArrayList<String> pCond, String pExUpd) throws Exception{
		Field[] fieldlist = pObj.getClass().getFields();
		StringBuilder sbSql = new StringBuilder();
		ArrayList<Object> objs = new ArrayList<Object>();
		sbSql.append("update "+pTabName+" set ");
		
		HashMap<String, Field> fieldMap = new HashMap<String, Field>();
		for(int i=0;i<fieldlist.length;i++){
			String columnName = fieldlist[i].getName().toUpperCase();
			fieldMap.put(columnName, fieldlist[i]);
		}
		
		//遍历更新的字段
		for(int i=0;i<pUpd.size();i++){
			String colName = pUpd.get(i).toUpperCase();
			if(!fieldMap.containsKey(colName)){
				throw new Exception("对象不存在字段"+colName);
			}
			if(objs.size() > 0){
				sbSql.append(",");
			}
			sbSql.append(colName+"=?");
			Field eachFd = fieldMap.get(colName);
			String eachType = eachFd.getGenericType().toString().toLowerCase();
			Object val = eachFd.get(pObj);
			if(eachType.contains("date") && val!=null){
				objs.add(new SimpleDateFormat(Format.DateIsoFormatStr).format(val));
			}else{
				objs.add(val);
			}
		}
		if(StringHelper.hasAnyChar(pExUpd) && pExUpd.trim().length()>0){
			sbSql.append(","+pExUpd);
		}
		sbSql.append(" where ");
		//遍历条件字段
		for(int i=0;i<pCond.size();i++){
			String colName = pCond.get(i).toUpperCase();
			if(!fieldMap.containsKey(colName)){
				throw new Exception("对象不存在字段"+colName);
			}
			if(i>0){
				sbSql.append(" and ");
			}
			Field eachFd = fieldMap.get(colName);
			String eachType = eachFd.getGenericType().toString().toLowerCase();
			Object val = eachFd.get(pObj);
			if(val == null){
				sbSql.append(colName+" is null");
			}else{
				sbSql.append(colName+"=?");
				if(eachType.contains("date") && val!=null){
					objs.add(new SimpleDateFormat(Format.DateIsoFormatStr).format(val));
				}else{
					objs.add(val);
				}
			}
		}
		
		int rowAff = JDBCHelper.update(pConn,sbSql.toString(), objs.toArray());
        return rowAff;
	}
}
